VERSION 0.6
FROM earthly/dind:alpine
WORKDIR /scala-example
RUN apk add openjdk11 bash wget postgresql-client

sbt: 
    #Scala
    # Defaults if not specified
    ARG sbt_version=1.3.2
    ARG sbt_home=/usr/local/sbt

    # Download and extract from archive
    RUN mkdir -pv "$sbt_home"
    RUN wget -qO - "https://github.com/sbt/sbt/releases/download/v$sbt_version/sbt-$sbt_version.tgz" >/tmp/sbt.tgz
    RUN tar xzf /tmp/sbt.tgz -C "$sbt_home" --strip-components=1
    RUN ln -sv "$sbt_home"/bin/sbt /usr/bin/

    # This triggers a bunch of useful downloads.
    RUN sbt sbtVersion

project-files:
    FROM +sbt
    COPY build.sbt ./
    COPY project project
    # Run sbt for caching purposes.
    RUN touch a.scala && sbt compile && rm a.scala
    SAVE IMAGE --push earthly/examples:integration-project-files

build:
    FROM +project-files
    COPY src src
    RUN sbt compile

unit-test:
    FROM +project-files
    COPY src src
    RUN sbt test

integration-test:
    FROM +project-files
    COPY src src
    COPY docker-compose.yml ./ 
    WITH DOCKER --compose docker-compose.yml
        RUN while ! pg_isready --host=localhost --port=5432 --dbname=iso3166 --username=postgres; do sleep 1; done ;\
            sbt it:test
    END

docker:
    FROM +project-files
    COPY src src
    RUN sbt 'set test in assembly := {}' assembly
    ENTRYPOINT ["java","-cp","target/scala-2.12/scala-example-assembly-1.0.jar","Main"]
    SAVE IMAGE --push earthly/examples:integration

smoke-test:
    FROM +project-files
    COPY docker-compose.yml ./
    COPY src/smoketest ./
    WITH DOCKER --compose docker-compose.yml --load=+docker
        RUN while ! pg_isready --host=localhost --port=5432 --dbname=iso3166 --username=postgres; do sleep 1; done ;\
            ./smoketest.sh
    END
    
all:
  BUILD +build
  BUILD +unit-test
  BUILD +integration-test
  BUILD +smoke-test
